# -*- coding: utf-8 -*-
import os

from django.http import HttpResponse
from django.shortcuts import render, reverse, redirect
from django.urls import resolve

# Create your views here.
from django.shortcuts import render

#base
from base.file.pubfile import *
from base.check.pubcheck import *

#git branch helper
from base.git_bran_helper import *



def index(request):
    value = 'This is test!'
    print(value)
    # kwargs = {'year':2010,'month':12,'day':10}
    # args= ['2019','12','12']
    # print(reverse('index:mydate', args=args))
    # print(reverse('index:mydate', kwargs=args))
    # return HttpResponse(reverse('index:mydate', args=args))
    # # return HttpResponse(reverse('index:mydate', args=args), **kwargs)
    return render(request, 'index.html')

    # print(reverse('index:turnTo')) #没有此视图
    # return redirect(reverse('index:mydate',args=[2019,12,12]))  #可以成功


def myvariables(request, year, month, day):
    return HttpResponse(str(year) + "/" + str(month) + "/" + str(day))


def mydate(request, year, month, day):
    # args = ['2019','01','12']
    # 先使用reverse，再使用resolve
    # result = resolve(reverse("index:mydate", args=args))
    result = resolve(reverse("index:mydate", args=[year, month, day]))
    print("kwargs:", result.kwargs)
    print("url_name:", result.url_name)
    print("namespace:", result.namespace)
    print("view_name:", result.view_name)
    print("app_name:", result.app_name)
    return HttpResponse(str(year) + "/" + str(month) + "/" + str(day))


def tpl(request):
    name = "小明"
    roles = ['管理员', 'CEO', '保安']
    user_info = {"name": "张力", "salary": 100000, "role": "CEO"}
    data_list = [
        {"name": "张力", "salary": 100000, "role": "CEO"},
        {"name": "宋晓晓", "salary": 100000, "role": "CEO"},
        {"name": "李四", "salary": 100000, "role": "CEO"}
    ]
    return render(request, 'tpl.html', {"n1": name, "n2": roles, "n3": user_info, "n4": data_list})


def news(request):
    # 1.定义一些新闻（字典或
    # 第三方模块:requests
    import requests
    response = requests.get("https://tushare.pro/wctapi/documents/95/api_info")
    data_list = response.json()
    print(data_list)

    return render(request, 'news.html', {"new_list": data_list})


def something(request):
    print("request.method", request.method)
    print(request.GET)
    print(request.POST)

    # [响应]HttpResponse("返回内容")，内容字符串内容返回给请求者
    # return HttpResponse("返回内容")

    # [响应]读取HTML的内容+渲染(替换）-->字符串，返回给用户浏览器
    return render(request, 'something.html', {"title": "来了"})

    # 重定向，浏览器向某个网址发送请求，网站告诉你去别的地方，浏览器就去告诉的地方了。这样减少了网站的压力。
    # return redirect("https://www.baidu.com/")


def login(request):
    if (request.method == "GET"):
        return render(request, 'login.html')

    username = request.POST.get("username")
    password = request.POST.get("pwd")
    if (username == "root" and password == "123"):
        # return HttpResponse("登陆成功")
        return redirect("https://www.baidu.com")

    # return HttpResponse("登陆失败")
    return render(request, 'login.html', {"error_msg": "用户名或密码错误"})


def stock(request):
    # if (request.method == "GET"):
    #     return HttpResponse("不支持")

    stock_code = request.POST.get("stock_code")
    querynum = request.POST.get("querynum")
    if (stock_code == "tushare"):
        return redirect("https://tushare.pro/")

    if (stock_code == None or len(stock_code) == 0):
        stock_code = "002848.SZ"
        querynum = 100
    if (querynum == None or len(str(querynum)) == 0):
        querynum = 10
    else:
        querynum = int(querynum)



    # 导入tushare
    import tushare as ts
    # 初始化pro接口
    pro = ts.pro_api('013c219eac0f41e6bab656721851c6e5bda0fa6343a98c270598f492')
    # # 拉取数据
    # df = pro.daily(**{
    #     "ts_code": "002848.SZ",
    #     "trade_date": "",
    #     "start_date": "",
    #     "end_date": "",
    #     "offset": 0,
    #     "limit": 10
    # }, fields=[
    #     "ts_code",
    #     "trade_date",
    #     "open",
    #     "high",
    #     "low",
    #     "close",
    #     "pre_close",
    #     "change",
    #     "pct_chg",
    #     "vol",
    #     "amount"
    # ])
    # 拉取数据
    df = pro.daily(**{
        "ts_code": stock_code,
        "trade_date": "",
        "start_date": "",
        "end_date": "",
        "offset": 0,
        "limit": querynum
    })

    result = ""
    for item in df:
        print('item:', item)
        result += str(item) + " "

    data_list = []
    head_list = []
    # data_list += ["No " + result]

    for i in df.index.values:
        print('index:', i, 'value:', df.loc[i, 'close'])
        # inexpress = "%-3s %-10s %-10s %-8s %-8s %-8s %-8s %-8s %-8s %-13s %-13s %-13s " % ( str(i),
        #                                 str(df.loc[i, 'ts_code']),
        #                                 str(df.loc[i, 'trade_date']),
        #                                 str(df.loc[i, 'open']),
        #                                 str(df.loc[i, 'high']),
        #                                 str(df.loc[i, 'low']),
        #                                 str(df.loc[i, 'close']),
        #                                 str(df.loc[i, 'pre_close']),
        #                                 str(df.loc[i, 'change']),
        #                                 str(df.loc[i, 'pct_chg']),
        #                                 str(df.loc[i, 'vol']),
        #                                 str(df.loc[i, 'amount']));
        # inexpress = inexpress.replace(" ", "*")
        # result = [ inexpress ]
        # print("result:", result)

        # data_list += result

        inexpress = [str(i),
                     str(df.loc[i, 'ts_code']),
                     str(df.loc[i, 'trade_date']),
                     str(df.loc[i, 'open']),
                     str(df.loc[i, 'high']),
                     str(df.loc[i, 'low']),
                     str(df.loc[i, 'close']),
                     str(df.loc[i, 'pre_close']),
                     str(df.loc[i, 'change']),
                     str(df.loc[i, 'pct_chg']),
                     str(df.loc[i, 'vol']),
                     str(df.loc[i, 'amount'])];
        result = [inexpress]
        print("result:", result)

        data_list += result

    head_list = ['No', 'ts_code', 'trade_date', 'open', 'high', 'low', 'close', 'pre_close', 'change', 'pct_chg', 'vol', 'amount']
    stock_list = ['601360.SH -360', '002960.SZ -青岛消防', '000063.SZ -中兴','002848.SZ -高斯贝尔','600602.SH -云赛智联','002405.SZ -四维图新' ]

    stock_path = getcurrentpath() + os.sep + "static" + os.sep +  "txt" + os.sep + "stocklist.txt"
    tmplist = fileread(stock_path)
    print(getcurrentpath())
    print(stock_path)
    print(tmplist)
    stock_list= tmplist.split('\n')
    return render(request, 'stock.html', {"title": "股票行情",
                                          "stock_code": stock_code,
                                          "stock_list": stock_list,
                                          "querynum": querynum,
                                          "head_list": head_list,
                                          "data_list": data_list,})


def calulator(request):
    # print(request.get_host())
    express = request.POST.get("express")
    calcresult = ""
    if (express != None) and len(express) > 0:
        print("express:", express)
        calcresult = eval(express)
    else:
        express = ""
        print("express:", express)
    return render(request, "calulator.html", {"express": express, "calcresult": calcresult})

def branchhelper(request):
    gitrootpath = request.POST.get("gitrootpath")
    branches = request.POST.get("branches")
    searchtext = request.POST.get("searchtext")
    isshowdiff = request.POST.get("isshowdiff")
    calcresult = ""

    gitrootpath= pubcheckstring(gitrootpath)
    branches= pubcheckstring(branches)
    searchtext= pubcheckstring(searchtext)
    isshowdiff= pubcheckstring(isshowdiff)

    print("gitrootpath:" + str(gitrootpath))
    print("branches:" + str(branches))
    print("searchtext:" + str(searchtext))
    print("isshowdiff:" + str(isshowdiff))

    returncode, showtips, diff_result, return_result1, search_result1, return_result2, search_result2 = gitbranchescheck(gitrootpath, branches, searchtext, isshowdiff)
    if False == returncode:
        print("showtips:", showtips)
        calcresult = "未找到:" + showtips
    else:
        print("showtips:", showtips)

    return render(request, "branchhelper.html", {"gitrootpath": gitrootpath,
                                                 "branches":branches,
                                                 "searchtext":searchtext,
                                                 "diff_result":diff_result,
                                                 "return_result1":return_result1,
                                                 "search_result1":search_result1,
                                                 "return_result2":return_result2,
                                                 "search_result2":search_result2,
                                                 "isshowdiff": isshowdiff,
                                                 "calcresult": calcresult
                                                 })
